<?php

namespace app\shop\controller;


use think\Db;
use think\Request;
use think\Exception;
use app\shop\model\Promotion as PromotionModel;

class Promotion extends \ShopController
{
    public function getpromotion(Request $request){
        $post = $request->param();
        try {
            $Pro=new PromotionModel();
            $client_id=$post["client_id"];
            $level_id=db("client")->where(["client_id"=>$client_id])->value("level_id");
            //$this->successTerminate($data);
            $now=date("Y-m-d H:i:s");
            $wherec="cus_list=$client_id or cus_list like '{$client_id},%' or cus_list like '%,{$client_id}' or cus_list like '%,{$client_id},%'";
            $whered="start_time<='{$now}' and end_time>'$now' ";

            $order=db("promotion")->where($wherec)->where($whered)->where("promotion_cate=2")->field("promotion_id,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->find();
            if(!$order){
                $order=db("promotion")->where(["cus_level"=>$level_id])->where($whered)->where("promotion_cate=2")->field("promotion_id,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->find();
            }
            if(!$order){
                $order=db("promotion")->where(["cus_level"=>9999])->where($whered)->where("promotion_cate=2")->field("promotion_id,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->find();
            }
            $order["promotion_rule"]=json_decode($order["promotion_rule"],true);
            $data["order"]=$order;
            $pc=db("promotion")->where($wherec)->where($whered)->where("promotion_cate=1")->field("promotion_id,promotion_goods,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->select();
            $pc1=db("promotion")->where(["cus_level"=>$level_id])->where($whered)->where("promotion_cate=1")->field("promotion_id,promotion_goods,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->select();
            $pc2=db("promotion")->where(["cus_level"=>9999])->where($whered)->where("promotion_cate=1")->field("promotion_id,promotion_goods,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->select();
            $pids=[];
            $product=[];
            foreach ($pc as $k => $v) {
                # code...
                $pc[$k]["promotion_rule"]=json_decode($pc[$k]["promotion_rule"],true);
                $pids[]=$v["promotion_goods"];
                $product[]=$pc[$k];
            }
            foreach ($pc1 as $k => $v) {
                # code...
                if(!in_array($v["promotion_goods"],$pids)){
                    $pc1[$k]["promotion_rule"]=json_decode($pc1[$k]["promotion_rule"],true);
                    $pids[]=$v["promotion_goods"];
                    $product[]=$pc1[$k];
                }
                
            }
            foreach ($pc2 as $k => $v) {
                # code...
                if(!in_array($v["promotion_goods"],$pids)){
                    $pc2[$k]["promotion_rule"]=json_decode($pc2[$k]["promotion_rule"],true);
                    $pids[]=$v["promotion_goods"];
                    $product[]=$pc2[$k];
                }
                
            }
            $data["product"]=$product;
            $gc=db("promotion")->where($wherec)->where($whered)->where("promotion_cate=3")->field("promotion_id,group_goods,group_goods_count,promotion_type,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->select();
            $gc1=db("promotion")->where(["cus_level"=>$level_id])->where($whered)->where("promotion_cate=3")->field("promotion_id,group_goods,group_goods_count,promotion_type,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->select();
            $gc2=db("promotion")->where(["cus_level"=>9999])->where($whered)->where("promotion_cate=3")->field("promotion_id,group_goods,group_goods_count,promotion_type,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->select();
            $pidgs=[];
            $group=[];
            foreach ($gc as $k => $v) {
                # code...
                $gc[$k]["promotion_rule"]=json_decode($gc[$k]["promotion_rule"],true);
                $p=explode(',',$v["group_goods"]);
                for($i=0;$i<count($p);$i++){
                    $pidgs[]=$p[$i];
                }
                $group[]=$gc[$k];
            }
            foreach ($gc1 as $k => $v) {
                # code...
                $p=explode(',',$v["group_goods"]);
                $flag=0;
                for($i=0;$i<count($p);$i++){
                    if(in_array($p[$i],$pidgs)){
                        $flag=1;break;
                    }
                }
                if($flag==0){
                    $gc1[$k]["promotion_rule"]=json_decode($gc1[$k]["promotion_rule"],true);

                    for($i=0;$i<count($p);$i++){
                        $pidgs[]=$p[$i];
                    }
                    $group[]=$gc1[$k];
                }
                
            }
            foreach ($gc2 as $k => $v) {
                # code...
                $p=explode(',',$v["group_goods"]);
                $flag=0;
                for($i=0;$i<count($p);$i++){
                    if(in_array($p[$i],$pidgs)){
                        $flag=1;break;
                    }
                }
                if($flag==0){
                    $gc2[$k]["promotion_rule"]=json_decode($gc2[$k]["promotion_rule"],true);

                    for($i=0;$i<count($p);$i++){
                        $pidgs[]=$p[$i];
                    }
                    $group[]=$gc2[$k];
                }
                
            }
            $data["group"]=$group;
            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
       
        } 
    }
    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {

        $post = $request->param();

        try {
            $Pro=new PromotionModel();
            $cus_level=json_decode($post["cus_level"]);
            unset($post["cus_level"]);
            $cus_list=[];
            if($post["checkAll"]==="true"){
                $cus_level=[9999];
            }else{
                if($post["designated"]){
                    $cus_list=json_decode($post["cus_list"]);
                }
            }
            unset($post["checkAll"]);
            unset($post["cus_list"]);
            unset($post["designated"]);

            $prolist=[];
            if(isset($post["prolist"])){
                $tmpprolist=json_decode($post["prolist"],true);
               // print_r($tmpprolist);die;
                foreach ($tmpprolist as $k => $v) {
                    # code...
                    if(isset($v["goods_sn"])){
                        $prolist[]=$tmpprolist[$k];
                    }

                }
                unset($post["prolist"]);
            }

            if($post["promotion_cate"]==1){
                if(!$prolist){
                    \exception("至少选择一个活动商品");
                }
            }
            $prozuhe=[];
            if(isset($post["prozuhe"])){
                $tmpprozuhe=json_decode($post["prozuhe"],true);
                foreach ($tmpprozuhe as $k => $v) {
                    # code...
                    if(isset($v["goods_sn"])){
                        $prozuhe[]=db("goods")->where(["goods_sn"=>$v["goods_sn"]])->value("goods_id");
                    }

                }
                unset($post["prozuhe"]);
            }
            if($post["promotion_cate"]==3){
                if(!$prozuhe){
                    \exception("至少选择两个活动商品");
                }
                if(count($prozuhe)<2){
                    \exception("至少选择两个活动商品");
                }
            }
            if(!($cus_level||$cus_list)){
                \exception("至少选择一个有效客户");
            }
            $post["start_time"]=date("Y-m-d H:i:s",strtotime($post["start_time"]));
            $post["end_time"]=date("Y-m-d H:i:s",strtotime($post["end_time"]));
            $post["is_step"]=="true"?$post["is_step"]=1:$post["is_step"]=0;
            $post["is_delete"]=0;
            $post["create_time"]=date("Y-m-d H:i:s");
            

            $detail=json_decode($post["promotion_detail"],true);

            foreach ($detail as $k => $v) {
                # code...
                if(!$v["full"]){
                    \exception("存在未填写的购买金额");
                }
                if(!$v["reduction"]){
                   \exception("存在未填写的优惠力度");
                }
            }
            
            $allpost=[];
            foreach ($cus_level as $k => $v) {
                # code...
                $allpost[$k]=$post;
                if($v!=9999)
                    $allpost[$k]["cus_level"]=db("client_level")->where(["level_name"=>$v])->value("level_id");
                else
                    $allpost[$k]["cus_level"]=9999;
                $allpost[$k]["cus_list"]=null;
            }

            if($cus_list){
                $tmpcus=$post;
                $tmpcus["cus_level"]=null;
                $tmpcus["cus_list"]=implode(',',$cus_list);
                
                $allpost[]=$tmpcus;
            }
            $allProPost=[];

            if($prolist){

                foreach ($prolist as $k => $v) {

                    $pid=db("goods")->where(["goods_sn"=>$v["goods_sn"]])->value("goods_id");
                    # code...
                    foreach ($allpost as $kp => $vp) {
                        # code...
                        $tmp=[];
                        $tmp=$vp;$tmp["promotion_goods"]=$pid;
                        $allProPost[]=$tmp;
                    }
                }
            }
            $pzhpost=[];
            if($prozuhe){
                foreach ($allpost as $kp => $vp) {
                        # code...
                    $tmp=[];
                    $tmp=$vp;$tmp["group_goods_count"]=count($prozuhe);
                    $tmp["group_goods"]=implode(',',$prozuhe);
                    $pzhpost[]=$tmp;
                }
            }
             
            if($post["promotion_cate"]==2){
                $check=$this->order_rep($allpost);
                if($check["success"])
                    $pid=$Pro->addpromotion($allpost);
                else
                    \exception($check["msg"]);
            }
            if($post["promotion_cate"]==1){

                $check=$this->pro_rep($allProPost);
                if($check["success"])
                    $pid=$Pro->addpromotion($allProPost);
                else
                    \exception($check["msg"]);
            }
            if($post["promotion_cate"]==3)
                $check=$this->zuhe_rep($pzhpost);
                if($check["success"])
                    $pid=$Pro->addpromotion($pzhpost);
                else
                    \exception($check["msg"]);
            
           
            $this->successTerminate($post);
          
         
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
       
        } 
    }
    //组合促销重复验证
    public function zuhe_rep($list){
        foreach ($list as $k => $v) {
           //判断商品促销
            $wheresp="is_delete=0 and promotion_cate=1 and promotion_goods in ({$v["group_goods"]}) and start_time<='{$v["end_time"]}' and end_time>='{$v["start_time"]}' ";
            $hassp=db("promotion")->where($wheresp)->find();

            if($hassp){
                 $product=db("goods")->where(["goods_id"=>$hassp["promotion_goods"]])->value("goods_name");
                return ["success"=>false,"msg"=>"产品{$product}已在{$hassp["start_time"]}至{$hassp["end_time"]}中参与了商品促销。"];
            }
            $pro=explode(',',$v["group_goods"]);
            foreach ($pro as $k1 => $v1) {
                # code...
                $where="is_delete=0 and promotion_cate=3 and (group_goods='{$v1}' or group_goods like '{$v1},%' or group_goods like '%,{$v1}' or group_goods like '%,{$v1},%') and start_time<='{$v["end_time"]}' and end_time>='{$v["start_time"]}' ";
                $has=db("promotion")->where($where)->find();
                if($has){
                    $product=db("goods")->where(["goods_id"=>$v1])->value("goods_name");
                    return ["success"=>false,"msg"=>"已存在产品{$product}{$has["start_time"]}至{$has["end_time"]}的组合促销"];
                }
            }
        }
        return ["success"=>true,"msg"=>""];
    }
    //商品促销重复验证
    public function pro_rep($list){
        foreach ($list as $k => $v) {
             $product=db("goods")->where(["goods_id"=>$v["promotion_goods"]])->value("goods_name");
            //组合促销验证
            $wherezuhe="is_delete=0 and promotion_cate=3 and (group_goods='{$v["promotion_goods"]}' or group_goods like '{$v["promotion_goods"]},%' or group_goods like '%,{$v["promotion_goods"]}' or group_goods like '%,{$v["promotion_goods"]},%') and start_time<='{$v["end_time"]}' and end_time>='{$v["start_time"]}' ";
            $haszuhe=db("promotion")->where($wherezuhe)->find();
            if($haszuhe){
                return ["success"=>false,"msg"=>"产品{$product}已在{$haszuhe["start_time"]}至{$haszuhe["end_time"]}中参与了组合促销。"];
            }
            # code...
            $where="is_delete=0 and promotion_cate=1 and promotion_goods={$v["promotion_goods"]} ";
            if($v["cus_level"]){
                $where.="and (cus_level={$v["cus_level"]} or cus_level=9999) ";
            }
            $where.="and start_time<='{$v["end_time"]}' and end_time>='{$v["start_time"]}' ";
            $where.="and promotion_province_code='{$v["promotion_province_code"]}' ";
            if($v["promotion_city_code"]){
                $where.="and promotion_city_code={$v["promotion_city_code"]} ";
            }else{
                $where.="and promotion_city_code='' ";
            }
            if($v["promotion_district_code"]){
                $where.="and promotion_district_code={$v["promotion_district_code"]} ";
            }else{
                $where.="and promotion_district_code='' ";
            }
            $has=db("promotion")->where($where)->find();
            if($has["cus_level"]==9999){
                $cus_level="全部客户";
            }else{
                $cus_level=db("client_level")->where(["level_id"=>$has["cus_level"]])->value("level_name");
            }
           
            if($has){
                return ["success"=>false,"msg"=>"商品促销--{$has["promotion_title"]}中，已存在产品{$product}{$has["start_time"]}至{$has["end_time"]}对于{$cus_level}的促销活动，不可重复"];
            }
        }
        return ["success"=>true,"msg"=>""];
    }
    //订单促销重复验证
    public function order_rep($list){
        foreach ($list as $k => $v) {
            # code...
            $where="is_delete=0 and promotion_cate=2 ";
            if($v["cus_level"]){
                $where.="and (cus_level={$v["cus_level"]} or cus_level=9999) ";
            }
            $where.="and start_time<='{$v["end_time"]}' and end_time>='{$v["start_time"]}' ";
            $where.="and promotion_province_code='{$v["promotion_province_code"]}' ";
            if($v["promotion_city_code"]){
                $where.="and promotion_city_code={$v["promotion_city_code"]} ";
            }else{
                $where.="and promotion_city_code='' ";
            }
            if($v["promotion_district_code"]){
                $where.="and promotion_district_code={$v["promotion_district_code"]} ";
            }else{
                $where.="and promotion_district_code='' ";
            }
            $has=db("promotion")->where($where)->find();
            if($has["cus_level"]==9999){
                $cus_level="全部客户";
            }else{
                $cus_level=db("client_level")->where(["level_id"=>$has["cus_level"]])->value("level_name");
            }
            if($has){

                return ["success"=>false,"msg"=>"订单促销--{$has["promotion_title"]}中，已存在{$has["start_time"]}至{$has["end_time"]}对于{$cus_level}的促销活动，不可重复"];
            }
        }
        return ["success"=>true,"msg"=>""];
    }
    //获取指定用户
    public function getcuslist(Request $request){
        try{
            $post= $request->param();
           
            $Pro=new PromotionModel();
            $arr=db("client")->field("client_id as `key`,client_name as `label`")->select();
            $this->successTerminate($arr);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
       
        }
        
    }
    //获取促销列表
    public function getlist(Request $request){
        $post = $request->param();
        try{
            $now=time();
            $page=$post["page"];
            $size=$post["size"];
            if(!$page)$page=1;
            $where["promotion_cate"]=$post["cate"];
           // 
            if(isset($post["title"])){
                if($post["title"]){
                    $where["promotion_title"]=["like","%{$post["title"]}%"];
                }
            }
            if(isset($post["state"])){
                if($post["state"]==2){
                    //未开始
                    $where["start_time"]=[">",date("Y-m-d H:i:s")];
                    $where["is_delete"]=0;
                }else if($post["state"]==3){
                    //促销中
                    $where["start_time"]=["<=",date("Y-m-d H:i:s")];
                    $where["end_time"]=[">=",date("Y-m-d H:i:s")];
                    $where["is_delete"]=0;
                }else if($post["state"]==4){
                    //已过期
                    $where["end_time"]=["<",date("Y-m-d H:i:s")];
                    $where["is_delete"]=0;
                }else if($post["state"]==5){
                    //已作废
                    $where["is_delete"]=1;
                }
            }
            $Pro=new PromotionModel();
            $back["num"]=$Pro->getpronum($where,$page,$size);

            $back["page"]=ceil($back["num"]/$size);
            $back["nowpage"]=$page;
            $back["size"]=$size;
            $prolist=db("promotion")->where($where)->limit(($page-1)*$size,$size)->select();
           // print_r($prolist);die;
            $backlist=[];
           // print_r($prolist);die;
            foreach ($prolist as $k => $v) {
                # code...
                $tmp["s_imgSrc"]="";
                $tmp["s_product"]=""; $tmp["s_guige"]="";
                if($v["promotion_goods"]){
                    $tmp["s_imgSrc"]=db("goods")->where(["goods_id"=>$v["promotion_goods"]])->value("goods_img");
                    $tmp["s_product"]=db("goods")->where(["goods_id"=>$v["promotion_goods"]])->value("goods_name");
                 
                }

                $tmp["s_id"]=$v["promotion_id"];
                $tmp["s_theme"]=$v["promotion_title"];
                $tmp["s_productNum"]=$v["group_goods_count"];
                if($v["promotion_rule"]==1){
                    $tmp["s_type"] ="满赠";    
                }else if($v["promotion_rule"]==2){
                    $tmp["s_type"] ="满减";          
                }else if($v["promotion_rule"]==3){
                    $tmp["s_type"] ="满折";          
                }else if($v["promotion_rule"]==4){
                    $tmp["s_type"] ="买赠";          
                }else if($v["promotion_rule"]==5){
                    $tmp["s_type"] ="直降";          
                }else if($v["promotion_rule"]==6){
                    $tmp["s_type"] ="打折";          
                }
                if($v["promotion_detail"]){
                    $tmpdet=json_decode($v["promotion_detail"],true);
                    //print_r($tmpdet);die;
                    $det_det=[];
                    foreach ($tmpdet as $k1 => $v1) {
                        # code...
                        if($v["promotion_rule"]==1){
                            $det_det[]="满{$v1["full"]}元赠{$v1["pname"]}中任意{$v1["reduction"]}件";
                        }else if($v["promotion_rule"]==2){
                            $det_det[]="满{$v1["full"]}元优惠{$v1["reduction"]}元";
                        }else if($v["promotion_rule"]==3){
                            $det_det[]="满{$v1["full"]}元打折{$v1["reduction"]}%";
                        }else if($v["promotion_rule"]==4){
                            $det_det[]="订货数量满{$v1["full"]}赠{$v1["pname"]}中任意{$v1["reduction"]}件";
                        }else if($v["promotion_rule"]==5){
                            $det_det[]="订货数量满{$v1["full"]}，订货价格统一减至{$v1["reduction"]}元";
                        }else if($v["promotion_rule"]==6){
                            $det_det[]="订货数量满{$v1["full"]}，打折{$v1["reduction"]}%";
                        }
                    }
                    $tmp["s_speces"]=$det_det[0];
                    $tmp["s_speces_all"]=$det_det;
                }else{
                    $tmp["s_speces"]="";
                    $tmp["s_speces_all"]="";
                }
                
                if($v["is_delete"]==1){
                    $tmp["s_state"]="已作废";$tmp["is_gray"]=true;
                }else if($now>strtotime($v["end_time"])){
                    $tmp["s_state"]="已过期";$tmp["is_gray"]=true;
                }else if($now<strtotime($v["start_time"])){
                    $tmp["s_state"]="未开始";$tmp["is_gray"]=true;
                }else{
                    $tmp["s_state"]="促销中";$tmp["is_gray"]=false;
                }
                $tmp["s_time"]=$v["start_time"]."至".$v["end_time"];
                $tmp["s_content"]="";
                $tmp["s_area"]=$v["promotion_province"];
                if($v["promotion_city"]) $tmp["s_area"].="/{$v["promotion_city"]}";
                if($v["promotion_district"]) $tmp["s_area"].="/{$v["promotion_district"]}";
                if($v["cus_list"]){
                    $tmp["s_obj"]="指定客户";
                    $tmp["s_objcus"]=db("client")->where("client_id in ({$v["cus_list"]})")->column("client_name");
                }
                else{
                    if($v["cus_level"]!=9999)
                        $tmp["s_obj"]=db("client_level")->where(["level_id"=>$v["cus_level"]])->value("level_name");
                    else
                        $tmp["s_obj"]="全部";
                    $tmp["s_objcus"]="";
                }
                $backlist[]=$tmp;
            }
            $back["prolist"]=$backlist;
            $this->successTerminate($back);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
       
        }
        
    }
    

    public function zuofei($pids){
        try{
            $Pro=new PromotionModel();
            $back=$Pro->fei($pids);
            $this->successTerminate($back);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
       
        }
    }
    public function shanchu($pids){
        try{
            $Pro=new PromotionModel();
            $back=$Pro->shan($pids);
            $this->successTerminate($back);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
       
        }
    }
}
